package com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp20;

import com.caiyi.financial.nirvana.sms.gateway.cmpp.CMPPHeader;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp20.message.CMPPBody;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp20.message.CMPPMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.List;

/**
 * CMPP消息解码
 *
 * @author lvchaohua
 */
public class CMPPStreamDecoder extends ByteToMessageDecoder {
    private static Logger logger = LogManager.getLogger(CMPPStreamDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext context, ByteBuf buff, List<Object> out) throws Exception {
        if (buff.readableBytes() <= 0) {
            return;
        }
//		logger.debug("cmpp decoder :"+ByteBufUtil.prettyHexDump(buff));
        try {
            CMPPMessage message = new CMPPMessage();

            CMPPHeader header = new CMPPHeader();
            header.decode(buff);
            message.setHeader(header);
            try {
                CMPPBody body = CMPPBody.decodeBody(message.getCommandID(), buff);
                message.setBody(body);
                message.setDecodeSuccess(true);
            } catch (Exception e) {
                logger.error("cmpp decode error!", e);
                message.setDecodeSuccess(false);
            }
            out.add(message);
        } catch (Exception e) {
            logger.error("channel:{}", context.channel());
            logger.error("cmpp decode error!", e);
        }
        if (buff.readableBytes() > 0) {
            logger.error("channel:{}", context.channel());
            logger.error("cmpp decode have remain bytes:" + ByteBufUtil.prettyHexDump(buff));
            byte[] temp = new byte[buff.readableBytes()];
            buff.readBytes(temp);
        }
    }
}
